package com.leetcode;

import com.leetcode.common.TreeNode;
import com.leetcode.util.BinaryTreeUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 236. 二叉树的最近公共祖先
 *
 * 1. 先分别找从root到p或p在树中的路径
 * 2. 通过比对路径, 找到第一个分叉的节点, 该节点就是最近公共祖先
 *
 * @author fy
 * @date 2022/4/26 22:12
 */
public class Solution236_2 {

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        List<TreeNode> pPath = getPath(root, p);
        List<TreeNode> qPath = getPath(root, q);
        TreeNode ancestor = null;
        for (int i = 0; i < pPath.size() && i < qPath.size(); ++i) {
            if (pPath.get(i) == qPath.get(i)) {
                ancestor = pPath.get(i);
            } else {
                break;
            }
        }
        return ancestor;
    }

    private List<TreeNode> getPath(TreeNode node, TreeNode p) {
        if (node == null) {
            return null;
        }
        // 这是递归的写法
        if (node.val == p.val) {
            List<TreeNode> list = new ArrayList<>();
            list.add(node);
            return list;
        }

        List<TreeNode> leftList = getPath(node.left, p);
        List<TreeNode> rightList = getPath(node.right, p);

        if (leftList == null && rightList == null) {
            return null;
        }
        List<TreeNode> list;
        if (leftList != null) {
            list = leftList;
        } else {
            list = rightList;
        }

        list.add(0, node);
        return list;
    }


    public static void main(String[] args) {
        Integer[] nums = new Integer[]{3, 5, 1, 6, 2, 0, 8, null, null, 7, 4};
        TreeNode root = BinaryTreeUtil.createTree(nums);
        BinaryTreeUtil.printTree(root);

        TreeNode p = new TreeNode(5);
        TreeNode q = new TreeNode(2);

        TreeNode node = new Solution236_2().lowestCommonAncestor(root, p, q);

        BinaryTreeUtil.printTree(node);
    }

}
